package arithmetic1.queue;

/*
    数组实现环形队列
 */
public class ArrayAsAnnulusQueue {
    /*
        tail指向最后一元素的后面一个位置，并将tail指向的位置永远留空,所以队列存储的大小等于maxSize-1
        求队列长度的公式: length=(tail+maxSize-1)%maxSize
        判断队列是否已满: (tail+1)%maxSize=head
     */
    private int maxSize;
    private int head=0;
    private int tail=0;
    private int arr[];

    //初始化队列
    public ArrayAsAnnulusQueue(int maxSize){
        this.maxSize=maxSize;
        this.arr=new int[maxSize];
    }

    //判断队列是否为空
    public boolean isEmpty(){
        if (head==tail){
            return true;
        }
        return false;
    }

    //判断队列是否已满
    public boolean isFull(){
        if((tail+1)%maxSize==head){
            return true;
        }else {
            return false;
        }
    }

    //向队列中添加一个元素
    public void add(int num){
        if(isFull()){   //队列已满
            System.out.println("队列已满,添加失败");
        }else{
            arr[tail]=num;
            //将尾指针后移
            tail=(tail+1)%maxSize;
        }
    }

    //删除队列的头元素,并返回
    public int remove(){
        int num;
        if(isEmpty()){ //队列为空
            throw new RuntimeException("队列为空,删除失败");
        }else{ //队列不为空
            num=arr[head];
            head=(head+1)%maxSize;
        }
        return num;
    }

    //返回队列长度
    public int length(){
        return (tail+maxSize-head)%maxSize;
    }

    //打印队列元素
    public void print(){
        for(int i=head;i<head+length();i++){
            System.out.print(arr[(i+maxSize)%maxSize]+"\t");
        }
        System.out.println();
    }


    public static void main(String[] args) {
        ArrayAsAnnulusQueue queue=new ArrayAsAnnulusQueue(5);
//        System.out.println(arithmetic1.queue.length());
        queue.add(10);
        queue.add(9);
        queue.add(4);
        queue.add(1);
        queue.remove();
        queue.remove();
        queue.add(2);
        queue.add(10);
        queue.print();
        System.out.println(queue.length());
    }
}
